/*
 * @Descripttion: 工具集
 * @version: 1.2
 * @LastEditors: sakuya
 * @LastEditTime: 2022年5月24日00:28:56
 */

import CryptoJS from 'crypto-js';
import sysConfig from "@/config";
import cache from "@/utils/cache";
import {h, resolveDynamicComponent} from "vue";
import {ElIcon} from "element-plus";
import {uuid} from "@tinymce/tinymce-vue/lib/es2015/main/ts/Utils";
import globalparam from "@/constant/model/globalparam";
import axios from "axios";
import ExImage from "@/components/exImage/index.vue";


const tool = {}

/* localStorage */
tool.data = {
	set(key, data, datetime = 0) {
		//加密
		if (sysConfig.LS_ENCRYPTION === "AES") {
			data = tool.crypto.AES.encrypt(JSON.stringify(data), sysConfig.LS_ENCRYPTION_key)
		}
		let cacheValue = {
			content: data,
			datetime: parseInt(datetime) === 0 ? 0 : new Date().getTime() + parseInt(datetime) * 1000
		}
		return localStorage.setItem(key, JSON.stringify(cacheValue))
	},
	get(key) {
		try {
			const value = JSON.parse(localStorage.getItem(key))
			if (value) {
				let nowTime = new Date().getTime()
				if (nowTime > value.datetime && value.datetime !== 0) {
					localStorage.removeItem(key)
					return null;
				}
				//解密
				if (sysConfig.LS_ENCRYPTION === "AES") {
					value.content = JSON.parse(tool.crypto.AES.decrypt(value.content, sysConfig.LS_ENCRYPTION_key))
				}
				return value.content
			}
			return null
		} catch (err) {
			return null
		}
	},
	remove(key) {
		return localStorage.removeItem(key)
	},
	clear() {
		localStorage.clear();
	},
}

/*sessionStorage*/
tool.session = {
	set(table, settings) {
		var _set = JSON.stringify(settings)
		return sessionStorage.setItem(table, _set);
	},
	get(table) {
		var data = sessionStorage.getItem(table);
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data;
	},
	remove(table) {
		return sessionStorage.removeItem(table);
	},
	clear() {
		return sessionStorage.clear();
	}
}

/*cookie*/
tool.cookie = {
	set(name, value, config = {}) {
		var cfg = {
			expires: null,
			path: null,
			domain: null,
			secure: false,
			httpOnly: false,
			...config
		}
		var cookieStr = `${name}=${escape(value)}`
		if (cfg.expires) {
			var exp = new Date()
			exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000)
			cookieStr += `;expires=${exp.toGMTString()}`
		}
		if (cfg.path) {
			cookieStr += `;path=${cfg.path}`
		}
		if (cfg.domain) {
			cookieStr += `;domain=${cfg.domain}`
		}
		document.cookie = cookieStr
	},
	get(name) {
		var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"))
		if (arr != null) {
			return unescape(arr[2])
		} else {
			return null
		}
	},
	remove(name) {
		var exp = new Date()
		exp.setTime(exp.getTime() - 1)
		document.cookie = `${name}=;expires=${exp.toGMTString()}`
	}
}

/* Fullscreen */
tool.screen = function (element) {
	var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
	if (isFull) {
		if (document.exitFullscreen) {
			document.exitFullscreen();
		} else if (document.msExitFullscreen) {
			document.msExitFullscreen();
		} else if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
		} else if (document.webkitExitFullscreen) {
			document.webkitExitFullscreen();
		}
	} else {
		if (element.requestFullscreen) {
			element.requestFullscreen();
		} else if (element.msRequestFullscreen) {
			element.msRequestFullscreen();
		} else if (element.mozRequestFullScreen) {
			element.mozRequestFullScreen();
		} else if (element.webkitRequestFullscreen) {
			element.webkitRequestFullscreen();
		}
	}
}

/* 复制对象 */
tool.objCopy = function (obj) {
	return JSON.parse(JSON.stringify(obj));
}

tool.toJsonString = function (obj) {
	return JSON.stringify(obj);
}
tool.toObj = function (jsonString) {
	return JSON.parse(jsonString);
}

tool.deleteTempProps = function (obj) {
	for (let prop in obj) {
		if (prop.startsWith("_")) {
			delete obj[prop];
		} else {
			if ((obj[prop] instanceof Object) && !Array.isArray(obj[prop])) {
				this.deleteTempProps(obj[prop]);
			}
		}
	}
}

tool.uuid = function (prefix) {
	if(!prefix){
		prefix="";
	}
	return uuid(prefix);
}

/* 日期格式化 */
tool.dateFormat = function (date, fmt = 'yyyy-MM-dd hh:mm:ss') {
	date = new Date(date)
	var o = {
		"M+": date.getMonth() + 1,                 //月份
		"d+": date.getDate(),                    //日
		"h+": date.getHours(),                   //小时
		"m+": date.getMinutes(),                 //分
		"s+": date.getSeconds(),                 //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		"S": date.getMilliseconds()             //毫秒
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for (var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
}

/* 千分符 */
tool.groupSeparator = function (num) {
	num = num + '';
	if (!num.includes('.')) {
		num += '.'
	}
	return num.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
		return $1 + ',';
	}).replace(/\.$/, '');
}

/* 常用加解密 */
tool.crypto = {
	//MD5加密
	MD5(data) {
		return CryptoJS.MD5(data).toString()
	},
	//BASE64加解密
	BASE64: {
		encrypt(data) {
			return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data))
		},
		decrypt(cipher) {
			return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8)
		}
	},
	//AES加解密
	AES: {
		encrypt(data, secretKey, config = {}) {
			if (secretKey.length % 8 != 0) {
				console.warn("[SCUI error]: 秘钥长度需为8的倍数，否则解密将会失败。")
			}
			const result = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(secretKey), {
				iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode[config.mode || "ECB"],
				padding: CryptoJS.pad[config.padding || "Pkcs7"]
			})
			return result.toString()
		},
		decrypt(cipher, secretKey, config = {}) {
			const result = CryptoJS.AES.decrypt(cipher, CryptoJS.enc.Utf8.parse(secretKey), {
				iv: CryptoJS.enc.Utf8.parse(config.iv || ""),
				mode: CryptoJS.mode[config.mode || "ECB"],
				padding: CryptoJS.pad[config.padding || "Pkcs7"]
			})
			return CryptoJS.enc.Utf8.stringify(result);
		}
	}
}

tool.format = {
	convert: function (value, formatter, key) {
		//其它格式转换，可以写成公用函数，然后调用
		if (formatter === 'ID_CARD' && value) {
			let len = value.length;
			return value.substr(0, 6) + ' **** **** ' + value.substr(len - 4, len);
		}

		if (formatter === 'NAME' && value) {
			let len = value.length;
			if (len > 2) {
				return value.substr(0, 1) + '*' + value.substr(len - 1, len);
			} else {
				return value.substr(0, 1) + '*';
			}
		}

		if (formatter === 'PHONE' && value) {
			let len = value.length;
			return value.substr(0, 3) + '****' + value.substr(len - 4, len);
		}

		if (formatter === 'MONEY' && value) {
			return tool.groupSeparator(this.fenToYuan(value));
		}

		if (formatter === 'MONEY_YUAN' && value) {
			return tool.groupSeparator(value);
		}

		if (formatter === 'DATETIME' && value) {
			return this.dateFormat(value);
		}

		if (formatter === 'DATE' && value) {
			if (value.length > 8) {
				value = value.substring(0, 8);
			}
			return this.dateFormat(value);
		}

		if (formatter === 'ICON' && value) {
			return h(ElIcon, () => h(resolveDynamicComponent(value)));
		}

		if (formatter === 'IMAGE' && value) {
			return h(ExImage,{value: value});
		}

		if (formatter === 'DICT' && value) {
			return cache.dic.exLabel(key, value, true);
		}
		return value;
	},
	dateFormat: function (dateStr) { //日期格式化（年月日）
		let tmpDate = "";
		if (dateStr == null)
			return;
		if (dateStr.length === 4) {
			tmpDate = dateStr.replace(/(.{2})(.{2})/g, "$1-$2");
		} else if (dateStr.length === 8) {
			tmpDate = dateStr.replace(/(.{4})(.{2})(.{2})/g, "$1-$2-$3");
		} else if (dateStr.length === 14) {
			tmpDate = dateStr.substring(0, 4) + "-";
			tmpDate = tmpDate + dateStr.substring(4, 6) + "-";
			tmpDate = tmpDate + dateStr.substring(6, 8) + " ";
			tmpDate = tmpDate + dateStr.substring(8, 10) + ":";
			tmpDate = tmpDate + dateStr.substring(10, 12) + ":";
			tmpDate = tmpDate + dateStr.substring(12, 14);
		}
		return tmpDate;
	},
	fenToYuan: function (val) {
		//金额转换 分->元 保留2位小数 并每隔3位用逗号分开 1,234.56
		var str = (val / 100).toFixed(2) + '';
		var intSum = str.substring(0, str.indexOf(".")).replace(/\B(?=(?:\d{3})+$)/g, ',');//取到整数部分
		var dot = str.substring(str.length, str.indexOf("."))//取到小数部分搜索
		var ret = intSum + dot;
		return ret;
	},
	yuanToFen: function (val) {
		return val * 100;
	},
}

tool.file = {
	open: async function (ossPath, download, fileName) {
		if (ossPath) {
			let serverUrl = await tool.minioServerUrl();
			let url = serverUrl + ossPath;
			if (download) {
				const xhr = new XMLHttpRequest();
				xhr.open("GET", url, true);
				xhr.responseType = "blob"; // 通过文件下载url拿到对应的blob对象
				xhr.onload = () => {
					if (xhr.status === 200) {
						let link = document.createElement("a");
						link.href = window.URL.createObjectURL(xhr.response);
						link.download = fileName;
						link.click();
						window.URL.revokeObjectURL(link.href);
					}
				};
				xhr.send();
			} else {
				window.open(url, "_blank");
			}
		}
	},
}

tool.current = {
	clear:function (){
		tool.data.remove("USER_INFO");
		tool.data.remove("CURRENT_ROLE");
		tool.data.remove("USER_ROLES");
		tool.data.remove("USER_MANAGE_DEPT_IDS");
		tool.data.remove("USER_READ_DEPT_IDS");
		tool.data.remove("CURRENT_ROLE");
		tool.data.remove("USER_POSITIONS");
		tool.data.remove("USER_POSITIONS");
		tool.data.remove("USER_INNER_RANGE_DEPT_IDS");
		tool.data.remove("USER_TOKEN");
	},
	user: function () {
		return tool.data.get("USER_INFO");
	},
	role: function () {
		return tool.data.get("CURRENT_ROLE");
	},
	roles: function () {
		return tool.data.get("USER_ROLES");
	},
	manageDeptIds: function () {
		return tool.data.get("USER_MANAGE_DEPT_IDS");
	},
	manageAssetCategoryIds: function () {
		return tool.data.get("CURRENT_ROLE").manageAssetCategoryIds;
	},
	readDeptIds: function () {
		return tool.data.get("USER_READ_DEPT_IDS");
	},
	readAssetCategoryIds: function () {
		return tool.data.get("CURRENT_ROLE").readAssetCategoryIds;
	},
	managePositionIds: function () {
		let data = tool.data.get("USER_POSITIONS");
		if(!data){
			data = [];
		}
		return data;
	},
	innerRangeDeptIds: function () {
		return tool.data.get("USER_INNER_RANGE_DEPT_IDS");
	},
	token: function () {
		return tool.data.get("USER_TOKEN");
	},
	socketId: function () {
		return this.user().id + "_"+this.token().tokenId +"_"+ this.role().id + "_" + this.user().orgId;
	},
	datetime: function () {
		return tool.data.get("CURRENT_ROLE");
	},
}

tool.minioServerUrl = async function () {
	return await cache.data.loadGlobalParam(globalparam.minioServerUrl.paramCode);
}

tool.oaDocumentServerUrl = async function () {
	return await cache.data.loadGlobalParam(globalparam.oaDocumentServerUrl.paramCode);
}

tool.excelTemplate = function (tableHeader, tableData, dom) {
	// 生成XLS文件内容
	let content = '';
	content += tableHeader.join('\t') + '\n'; // 添加表头
	for (let row of tableData) {
		content += row.join('\t') + '\n'; // 添加数据行
	}
	// 创建Blob对象
	const blob = new Blob([content], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8;'});
	// 创建下载链接
	const downloadLink = dom.createElement('a');
	downloadLink.href = URL.createObjectURL(blob);
	downloadLink.download = tool.uuid("temp") + '.xlsx';
	// 模拟点击下载链接
	downloadLink.click();
}

export default tool
